package org.minproject.my_library_back.controller;

import jakarta.annotation.Resource;
import org.minproject.my_library_back.common.CommonResponse;
import org.minproject.my_library_back.domain.User;
import org.minproject.my_library_back.service.UserService;
import org.springframework.web.bind.annotation.*;

@RestController
public class UserController {
    @Resource
    private UserService usersService;

    //用户注册
    @PostMapping("/users/register")
    public CommonResponse<User> register(@RequestBody User user) throws Exception {
        if (user == null || user.getUserId() == null || user.getUserName() == null || user.getUserPassword() == null || user.getUserPower() == null || user.getUserPicture() == null) {
            return CommonResponse.createForError("所有信息均不能为空");
        }
        return usersService.register(user);
    }



    //使用userid和password登录图书管理系统
    @PostMapping("/users/{userid}/{password}")
    public CommonResponse<User> login(@PathVariable("userid") String userid, @PathVariable("password") String password) throws Exception {
        if (userid == null || userid.isEmpty() || password == null || password.isEmpty()) {
            return CommonResponse.createForError("Missing userid or password");
        }
        return usersService.login(userid, password);
    }

    //获取所有用户信息
    @GetMapping("/users")
    public ResponseEntity<CommonResponse<CollectionModel<User>>> getUsers() {
        logger.info("Getting all users");
        List<User> users = userService.getAllUsers();

        // 创建包含链接的 CollectionModel
        CollectionModel<User> userCollectionModel = CollectionModel.of(users,
                WebMvcLinkBuilder.linkTo(WebMvcLinkBuilder.methodOn(UserController.class).getUsers()).withSelfRel(),
                WebMvcLinkBuilder.linkTo(WebMvcLinkBuilder.methodOn(UserController.class).getUsersByUserIdLike(1)).withRel("createUser")
        );

        return ResponseEntity.ok(CommonResponse.createForSuccess(userCollectionModel));
    }

    //添加用户
    @PostMapping("/users/add")
    public ResponseEntity<CommonResponse<Integer>> addUser(@RequestBody User user) {
        logger.info("Adding user: {}", user);
        int result = userService.addUser(user);
        if (result > 0) {
            return ResponseEntity.status(HttpStatus.CREATED).body(CommonResponse.createForSuccess(result));
        } else {
            logger.error("Failed to add user: {}", user);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(CommonResponse.createForError("添加用户失败"));
        }
    }

    //根据id删除指定用户
    @DeleteMapping("/users/delete/{id}")
    public ResponseEntity<CommonResponse<Integer>> deleteUser(@PathVariable int user_id) {
        logger.info("Deleting user with ID: {}", user_id);
        int result = userService.deleteUser(user_id);
        if (result > 0) {
            return ResponseEntity.ok(CommonResponse.createForSuccess(result));
        } else {
            logger.warn("User not found with ID: {}", user_id);
            return ResponseEntity.notFound().build();
        }
    }

    //修改用户信息
    @PutMapping("/users/update")
    public ResponseEntity<CommonResponse<Integer>> updateUser(@RequestBody User user) {
        logger.info("Updating user: {}", user);
        int result = userService.updateUser(user);
        if (result > 0) {
            return ResponseEntity.ok(CommonResponse.createForSuccess(result));
        } else {
            logger.warn("User not found: {}", user);
            return ResponseEntity.notFound().build();
        }
    }

    //根据id模糊查询用户
    @GetMapping("/users/{id}")
    public ResponseEntity<CommonResponse<CollectionModel<User>>> getUsersByUserIdLike(@PathVariable int user_id) {
        logger.info("Searching users with user_id like: {}", user_id);
        List<User> users = userService.getUsersByUserIdLike(user_id);

        if (users.isEmpty()) {
            logger.warn("No users found with user_id like: {}", user_id);
            return ResponseEntity.notFound().build();
        } else {
            // 创建包含链接的 CollectionModel
            CollectionModel<User> userCollectionModel = CollectionModel.of(users,
                    WebMvcLinkBuilder.linkTo(WebMvcLinkBuilder.methodOn(UserController.class).getUsers()).withRel("getUserById")
            );

            return ResponseEntity.ok(CommonResponse.createForSuccess(userCollectionModel));
        }
    }
}
